<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  @close="closeDialog"
	  size="750"
	  class="custom-drawer"
	  header-class="custom-drawer-header"
	  :close-on-click-modal="false"
	>
	<el-scrollbar  style="padding-left: 0.5rem;padding-right: 0.5rem;">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基本信息" name="basic">
				<BasicFormItem ref="basicFormRef" :data="formData?.basic"></BasicFormItem> 
			</el-tab-pane>
			<el-tab-pane label="连接配置" name="connection">
				<ConnectionPane ref="connectionFormRef" :data="formData?.connection"></ConnectionPane>
			</el-tab-pane>
			<el-tab-pane label="认证配置" name="authorization">
				<AuthorizationPane ref="authorizationFormRef" :data="formData?.authorization"></AuthorizationPane>
			</el-tab-pane>
		</el-tabs>
	</el-scrollbar>
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
			<el-button 
			  type="success" 
			  @click="handleTest" 
			  :loading="loading" 
			  :disabled="!formData?.basic?.id"
			>测 试</el-button>
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
	</el-drawer>
</template>

<script lang="ts" setup>
	import { DatasourceConfigService } from '@/api/data-collection/datasourceConfig'
	import MonacoEditor from '@/components/MonacoEditor/index.vue'
	import EditParamFieldDrawer from '@/components/DataWorkflow/components/EditParamFieldDrawer.vue';
	import {BasicField,DbConnectionField,DbAuthField,DbFormData} from '@/components/DataWorkflow/types/data-collect.ts';
	import { ref } from 'vue-demi';
	import BasicFormItem from './common/BasicFormItem.vue'
	import ConnectionPane from './database/ConnectionPane.vue'
	import AuthorizationPane from './database/AuthorizationPane.vue'
	import { ElMessage } from 'element-plus';
	
	const emits = defineEmits(['closeDialog'])
	const activeTab=ref<string>('basic')
	const loading = ref(false);
	const rawjson=ref();
	const dialog = ref({
		visible: false,
		title: '',
	});
	
	const basicFormRef = ref();
	const connectionFormRef = ref();
	const authorizationFormRef = ref();
	
	const formData = ref<DbFormData>({
		basic: {
			id: '',
			name: '',
			description: '',
			status: false,
			type: 'DATABASE'
		},
		connection: {
			dbType: 'mysql',
			host: '',
			port: 3306,
			database: '',
			timeout: 30,
			poolSize: 5,
			charset: 'utf8',
		},
		authorization:{
			authMethod: 'password',
			encryption: 'none',
			connectionTimeout: 30,
			commandTimeout: 30,
			minTlsVersion: '1.2',
		}
	});
	
	async function openDialog( type?: string,row?: any) {
		resetForm();
		if(row){
			formData.value.basic = {
				id:row.id,
				name:row.name,
				description:row.description,
				status:row.status,
				type:'DATABASE'
			}
			const connectionConfig = row.connectionConfig ? JSON.parse(row.connectionConfig) : {};
			formData.value.authorization = connectionConfig?.authorization ?? connectionConfig.authorization;
			formData.value.connection = connectionConfig?.connection ?? connectionConfig.connection;
		}
		dialog.value = {
			visible: true,
			title: type === 'add' ? '新增Database数据源' : '编辑Database数据源'
		};
	}
	
	const submitForm = async () => {
		const basic=await  basicFormRef.value.validate();
		if(!basic){
			activeTab.value='basic';
			return;
		}
		
		const connection=await  connectionFormRef.value.validate();
		if(!connection){
			activeTab.value='connection';
			return;
		}
		
		const authorization=await  authorizationFormRef.value.validate();
		if(!authorization){
			activeTab.value='authorization';
			return;
		}
		formData.value.connection=connectionFormRef.value.getData();
		formData.value.authorization=authorizationFormRef.value.getData();
		
		try{
			loading.value = true;
			formData.value.basic.type="DATABASE";
			await  DatasourceConfigService.save({
				...formData.value.basic,
				connectionConfig:JSON.stringify({
					authorization:formData.value.authorization,
					connection:formData.value.connection,
				})
			})
			ElMessage.success(formData.value.basic.id ? "更新成功.":"保存成功.");
			closeDialog();
		}catch(err){
			console.error(err);
		}finally{
			loading.value = false;
		}
	};
	
	const handleTest=async ()=>{
		try{
			loading.value = true;
			formData.value.basic.type="DATABASE";
			await  DatasourceConfigService.test(formData.value.basic.id,formData.value.basic.type);
			ElMessage.success("成功.");
			closeDialog();
		}catch(err){
			console.error(err);
		}finally{
			loading.value = false;
		}
	}
	
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emits('closeDialog',formData.value)
	}
	
	function resetForm() {
		formData.value={
			basic: {
				id: '',
				name: '',
				description: '',
				status: false,
				type: 'DATABASE'
			},
			connection: {
				dbType: 'mysql',
				host: '',
				port: 3306,
				database: '',
				timeout: 30,
				poolSize: 5,
				charset: 'utf8',
			},
			authorization:{
				authMethod: 'password',
				encryption: 'none',
				connectionTimeout: 30,
				commandTimeout: 30,
				minTlsVersion: '1.2',
			}
		};
	}	
	
	defineExpose({
	  openDialog,closeDialog
	});
	
</script>

<style scoped>

	
	
   .title-form_primary {
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		color: var(--art-text-gray-700) !important;
		position: relative;
		padding-left: 5px;
	}
	
	.title-form_primary:before {
	    content: "";
	    width: 2px;
	    height: 14px;
	    background: var(--el-color-primary);
	    position: absolute;
	    top: 50%;
	    transform: translateY(-50%);
	    left: 0;
	}
	
	.row-content {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		margin-bottom: 10px;
		gap: 5px;
		
		:deep(.el-select) {
			width: 120px;
		}
	}
	
	.body-raw-content {
		margin-top: 8px;
		width: 100%;
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	.editor {
		height: 400px;
		min-height: 250px;
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: 4px;
		flex: 1;
		min-width: 0;
		overflow: hidden;
	}

	.el-form-item {
		width: 100%;
	}

	.el-form-item__content {
		width: 100%;
	}

	.response-content {
		border: 1px solid var(--el-border-color);
		border-radius: 4px;
		overflow: hidden;
	}

	.test-result {
		.result-header {
			padding: 12px;
			display: flex;
			justify-content: space-between;
		align-items: center;
			border-bottom: 1px solid var(--el-border-color);
			
			.status-code {
				display: flex;
				align-items: center;
				gap: 8px;
				
				.label {
					font-weight: 500;
				}
			}
		}
		
		.response-editor {
			max-height: 400px;
			border: none;
		}
		
		.headers-list {
			padding: 12px;
			
			.header-item {
				padding: 4px 0;
				display: flex;
				gap: 8px;
				
				.header-name {
					color: var(--el-text-color-secondary);
					min-width: 120px;
				}
				
				.header-value {
					color: var(--el-text-color-primary);
					word-break: break-all;
				}
			}
		}
	}

	.response-body {
		position: relative;
		height: 300px;
		display: flex;
		flex-direction: column;
	}

	.response-toolbar {
		padding: 8px;
		border-bottom: 1px solid var(--el-border-color);
	}

	.response-content-wrapper {
		flex: 1;
		position: relative;
		overflow: hidden;
	}

	.empty-response {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: var(--el-fill-color-light);
	}

	.response-editor {
		height: 100%;
		width: 100%;
		overflow: hidden;
	}

	.pagination-settings {
		padding: 16px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
		margin-bottom: 18px;
	}
	
	.pagination-settings :deep(.el-form-item:last-child) {
		margin-bottom: 0;
	} 
</style>